<!--
 * @Descripttion: 
 * @version: 
 * @Author: wtzhang
 * @Date: 2021-11-11 16:02:09
 * @LastEditors: wtzhang
 * @LastEditTime: 2021-11-12 10:27:33
-->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>前端实现分页加载数据</title>
</head>
<body>
  <button onclick="require()">点击</button>
  <script>
    // 分页功能
	let curPage = 1; // 当前页
	let perPage = 3; // 每页展示条数
	let totalPage = 0; // 总分页数
  let start = 0; // 取值起点
  let end = 0; // 取值终点
  let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  let resArr = [] // 用来记录请求的数据累加状态
  /*
  * sort 排序类型 desc倒序 / asc正序
  */
  function require(sort = 'desc') {
    if (!(sort && typeof sort === 'string')) {
      alert('入参格式不对！')
      return
    }
    let totalLen = arr.length // 数据长度
    totalPage = Math.ceil(totalLen / perPage) // 总分页数
    totalPage = totalPage - curPage
    let curTotalNum = totalLen - end
    // 阻止
    if (totalPage < 0) {
      alert('没有更多啦~')
      return 
    }
    if (sort === 'asc') {
      // 阻止
      if (curTotalNum <= 0) {
        alert('没有更多啦~')
        return 
      }
      totalPage = totalPage - curPage
      end = curPage * perPage
      console.log(start, end, totalPage);
      resArr= resArr.concat(arr.slice(start, end))
      console.log(resArr);
      curPage++
      // console.log(start, end, curTotalNum);
      start = start + perPage
    } else {
      // 阻止
      if (totalPage < 0) {
        alert('没有更多啦~')
        return 
      }
      start = totalLen - (perPage * curPage) // 起止
      end = totalLen - ((curPage - 1) * perPage) // 终止
      console.log(start, end, totalPage);
      if (start <= 0) start = 0;
      resArr= resArr.concat(arr.slice(start, end))
      console.log(resArr);
      curPage++;
    }
  }
  </script>
</body>
</html>